package com.back.network.netty.utils;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONObject;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

public class CommonUtils {
	/**
	 * 输出HTML消息，并关闭信道
	 * 
	 * @param ctx
	 * @param content
	 */
	public static void writeAndFlush(ChannelHandlerContext ctx, String content) {

		// 1.设置响应
		FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
				Unpooled.copiedBuffer(JSONObject.toJSONString(content), CharsetUtil.UTF_8));

		resp.headers().set("content-type", "text/html; charset=UTF-8");

		// 2.发送
		// 注意必须在使用完之后，close channel
		ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
	}

	/**
	 * 构建Http响应
	 * 
	 * @param content
	 * @return
	 */
	public static FullHttpResponse getHttpResponse(String content) {
		try {
			FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
					Unpooled.wrappedBuffer(content.getBytes("utf-8")));
			response.headers().set(Names.CONTENT_TYPE, "text/plain;charset=UTF-8");
			response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
			response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解析请求头，获取访问域名
	 */
	public static String getHost(byte[] bytes) {
		String content = new String(bytes);
		String host = "";
		// 利用换行符做反向匹配
		String regex = ".+";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(content);
		while (matcher.find()) {
			String head = matcher.group(0);
			if (head.contains("Host: ")) {
				host = head.substring(5, head.length()).trim();
			}
		}
		return host;
	}
	
	/**
	 * 生成数字的随机字符串
	 */
	public static String getRandomString(int length) {
		String str = "0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(10);
			sb.append(str.charAt(number));
		}
		return sb.toString();
	}

}
